package com.jozen.smart_toilet_system.tagView;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.jozen.modelbase.netwoek.util.DensityUtil;
import com.jozen.smart_toilet_system.bean.BathroomModel;
import com.jozen.smart_toilet_system.bean.BathroomParameter;

import java.util.ArrayList;
import java.util.List;


/**
 * 自定义茅坑坑位配置layout
 */
public class PictureTagLayout extends RelativeLayout implements View.OnTouchListener {
    private static final int CLICKRANGE = 5;
    int startX = 0;
    int startY = 0;
    int startTouchViewLeft = 0;
    int startTouchViewTop = 0;
    private boolean isShowPop;//pop是否还是弹出状态
    private View touchView, clickView;
    private TagViewCallBack tagViewCallBack;
    private TagConfigPopup pop;
    private int width, height;
    private BathroomModel bathroomModel = new BathroomModel();

    public PictureTagLayout(Context context) {
        super(context, null);
    }

    public PictureTagLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PictureTagLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void init() {
        this.setOnTouchListener(this);
        pop = new TagConfigPopup(getContext());
    }


    public void setTagViewCallBack(TagViewCallBack tagViewCallBack) {
        this.tagViewCallBack = tagViewCallBack;
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!isShowPop) {
                    touchView = null;
                    if (clickView != null) {
                        ((PictureTagView) clickView).setStatus(PictureTagView.Status.Normal);
                        clickView = null;
                    }
                    startX = (int) event.getX();
                    startY = (int) event.getY();
                    if (hasView(startX, startY)) {//已经在目标位置添加过icon，不可做添加
                        startTouchViewLeft = touchView.getLeft();
                        startTouchViewTop = touchView.getTop();
                    } else {
                        addItem(startX, startY);
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                //可拖动
//                moveView((int) event.getX(),
//                        (int) event.getY());
                break;
            case MotionEvent.ACTION_UP:
                int endX = (int) event.getX();
                int endY = (int) event.getY();
                //如果挪动的范围很小，则判定为单击
                if (touchView != null && Math.abs(endX - startX) < CLICKRANGE && Math.abs(endY - startY) < CLICKRANGE) {
                    //点击已经添加过的tag
                    clickView = touchView;
                }
                touchView = null;
                break;
        }
        return true;
    }


    /**
     * 回显之前配置的坑位数据
     *
     * @param bathroomModel
     */
    public void setSettingData(BathroomModel bathroomModel) {
        if (bathroomModel != null && bathroomModel.getControls().size() > 0) {
            this.bathroomModel = bathroomModel;
            removeAllViews();
            invalidate();
            for (BathroomModel.ControlsDTO model : bathroomModel.getControls()) {
                showTag(model.getX(), model.getY(), model.getStatus(), model.isSos());
            }
        }
    }

    /**
     * 当前控件宽高
     *
     * @param w
     * @param h
     */
    public void setWidthHeight(int w, int h) {
        this.width = w;
        this.height = h;
    }


    /**
     * 显示已经添加过的蹲位传感器
     *
     * @param x
     * @param y
     */
    private void showTag(int x, int y, int state, boolean sos) {
        View view = null;
        LayoutParams params = new LayoutParams(DensityUtil.dip2px(getContext(), 50), DensityUtil.dip2px(getContext(), 50));
        params.width = DensityUtil.dip2px(getContext(), 50);
        params.height = DensityUtil.dip2px(getContext(), 50);
        if (x > getWidth() * 0.5) {
            params.leftMargin = x - PictureTagView.getViewWidth() + 25;
            view = new PictureTagView(getContext(), PictureTagView.Direction.Right);
        } else {
            params.leftMargin = x - 25;
            view = new PictureTagView(getContext(), PictureTagView.Direction.Left);
        }

        params.topMargin = y - 25;
        //上下位置在视图内
        if (params.topMargin < 0) {
            params.topMargin = 0;
        } else if ((params.topMargin + PictureTagView.getViewHeight()) > getHeight()) {
            params.topMargin = getHeight() - PictureTagView.getViewHeight();
            if (params.topMargin < 0) {
                params.topMargin = y - 25;
            }
        }

        view.setTag(x + "tag" + y);

        ((PictureTagView) view).setIcon(((PictureTagView) view).getBgIcon(state, sos),sos,state);

        view.setVisibility(VISIBLE);
        this.addView(view, params);

        View finalView = view;
        //每个添加的TagView设置点击监听事件
        finalView.setOnClickListener(v -> {
            PictureTagView tagView = (PictureTagView) v;
            String tag = (String) tagView.getTag();
            pop.dismiss();
            pop.setCallBack((actionType, object) -> {
                if (actionType == 1) {//清空当前配置
                    if (tagViewCallBack != null) {
                        if (bathroomModel != null
                                && bathroomModel.getControls().size() > 0) {
                            for (int i = 0; i < bathroomModel.getControls().size(); i++) {
                                if (bathroomModel.getControls().get(i).getX() == x && bathroomModel.getControls().get(i).getY() == y) {
                                    removeItem(tagView);
                                    bathroomModel.getControls().remove(i);
                                    pop.dismiss();
                                    break;
                                }
                            }
                            tagViewCallBack.call(3, bathroomModel);
                        }
                    }
                } else if (actionType == 2) {//修改探测器SN
                    BathroomParameter bathroomParameter = (BathroomParameter) object;
                    String snNo = bathroomParameter.getSnCode();
                    boolean isSos = bathroomParameter.isSos();
                    if (tagViewCallBack != null) {
                        if (bathroomModel != null
                                && bathroomModel.getControls().size() > 0) {
                            for (int i = 0; i < bathroomModel.getControls().size(); i++) {
                                if (bathroomModel.getControls().get(i).getX() == x && bathroomModel.getControls().get(i).getY() == y) {
                                    bathroomModel.getControls().get(i).setSnNo(snNo);
                                    bathroomModel.getControls().get(i).setSos(isSos);
                                    pop.dismiss();
                                    break;
                                }
                            }
                            tagViewCallBack.call(3, bathroomModel);
                        }
                    }
                }
            });

            pop.setOldSnCode("", false);
            //回显之前的值
            if (bathroomModel != null && bathroomModel.getControls() != null && bathroomModel.getControls().size() > 0) {
                if (bathroomModel != null
                        && bathroomModel.getControls().size() > 0) {
                    for (int i = 0; i < bathroomModel.getControls().size(); i++) {
                        if (bathroomModel.getControls().get(i).getX() == x && bathroomModel.getControls().get(i).getY() == y) {
                            pop.setOldSnCode(bathroomModel.getControls().get(i).getSnNo(), bathroomModel.getControls().get(i).isSos());
                            break;
                        }
                    }
                }
            }

            if (y > getHeight() * 0.5) {//到底部边缘，pop要调整显示的位置
                pop.showAsDropDown(tagView, (tagView.getLeft() - x) + 50, (tagView.getTop() - y) - 100);
            } else {
                pop.showAsDropDown(tagView, (tagView.getLeft() - x) + 25, (tagView.getTop() - y) + 25);
            }

        });
    }


    /**
     * 配置蹲位传感器
     *
     * @param x
     * @param y
     */
    private void addItem(int x, int y) {
        View view = null;
        LayoutParams params = new LayoutParams(DensityUtil.dip2px(getContext(), 50), DensityUtil.dip2px(getContext(), 50));
        if (x > getWidth() * 0.5) {
            params.leftMargin = x - PictureTagView.getViewWidth() + 25;
            view = new PictureTagView(getContext(), PictureTagView.Direction.Right);
        } else {
            params.leftMargin = x - 25;
            view = new PictureTagView(getContext(), PictureTagView.Direction.Left);
        }

        params.topMargin = y - 25;
        //上下位置在视图内
        if (params.topMargin < 0) {
            params.topMargin = 0;
        } else if ((params.topMargin + PictureTagView.getViewHeight()) > getHeight()) {
            params.topMargin = getHeight() - PictureTagView.getViewHeight();
            if (params.topMargin < 0) {
                params.topMargin = y - 25;
            }
        }

        view.setVisibility(INVISIBLE);
        this.addView(view, params);
        pop.dismiss();
        View finalView = view;
        pop.setCallBack((actionType, object) -> {
            if (actionType == 2) {//新增配置
                if (bathroomModel != null) {
                    BathroomParameter bathroomParameter = (BathroomParameter) object;
                    String snNo = bathroomParameter.getSnCode();
                    boolean isSos = bathroomParameter.isSos();
                    ((PictureTagView) finalView).setIcon(((PictureTagView) finalView).getBgIcon(0, isSos),isSos,0);

                    finalView.setVisibility(VISIBLE);
                    BathroomModel.ControlsDTO model = new BathroomModel.ControlsDTO();
                    model.setX(x);
                    model.setY(y);
                    model.setSnNo(snNo);
                    model.setSos(isSos);
                    if (bathroomModel.getControls() == null) {
                        List<BathroomModel.ControlsDTO> controls = new ArrayList<>();
                        bathroomModel.setControls(controls);
                    }
                    bathroomModel.getControls().add(model);
                    if (tagViewCallBack != null) {
                        tagViewCallBack.call(3, bathroomModel);
                    }
                }
            } else if (actionType == 1) {
                removeItem(finalView);
            } else {
                removeItem(finalView);
                Log.d("ZZZ=====", "空白处关闭");
            }
            pop.dismiss();
            isShowPop = false;
        });

        if (y > getHeight() * 0.5) {//到底部边缘，pop要调整显示的位置
            pop.showAsDropDown(view, x, y - 100);
        } else {
            pop.showAsDropDown(view, x, y + 25);
        }
        isShowPop = true;

        pop.setOldSnCode("", false);
        //每个添加的TagView设置点击监听事件
        finalView.setOnClickListener(v -> {
            PictureTagView tagView = (PictureTagView) v;
            String tag = (String) tagView.getTag();
            pop.dismiss();
            pop.setCallBack((actionType, object) -> {
                if (actionType == 1) {//清空当前配置
                    if (tagViewCallBack != null) {
                        if (bathroomModel != null
                                && bathroomModel.getControls().size() > 0) {
                            for (int i = 0; i < bathroomModel.getControls().size(); i++) {
                                if (bathroomModel.getControls().get(i).getX() == x && bathroomModel.getControls().get(i).getY() == y) {
                                    removeItem(tagView);
                                    bathroomModel.getControls().remove(i);
                                    pop.dismiss();
                                    break;
                                }
                            }
                            tagViewCallBack.call(3, bathroomModel);
                        }
                    }
                } else if (actionType == 2) {//修改配置探测器
                    String snNo = (String) object;
                    if (tagViewCallBack != null) {
                        if (bathroomModel != null
                                && bathroomModel.getControls().size() > 0) {
                            for (int i = 0; i < bathroomModel.getControls().size(); i++) {
                                if (bathroomModel.getControls().get(i).getX() == x && bathroomModel.getControls().get(i).getY() == y) {
                                    bathroomModel.getControls().get(i).setSnNo(snNo);
                                    pop.dismiss();
                                    break;
                                }
                            }
                            tagViewCallBack.call(3, bathroomModel);
                        }
                    }
                }
            });

            pop.setOldSnCode("", false);
            //回显之前的值
            if (bathroomModel != null && bathroomModel.getControls() != null && bathroomModel.getControls().size() > 0) {
                if (bathroomModel != null
                        && bathroomModel.getControls().size() > 0) {
                    for (int i = 0; i < bathroomModel.getControls().size(); i++) {
                        if (bathroomModel.getControls().get(i).getX() == x && bathroomModel.getControls().get(i).getY() == y) {
                            pop.setOldSnCode(bathroomModel.getControls().get(i).getSnNo(), bathroomModel.getControls().get(i).isSos());
                            break;
                        }
                    }
                }
            }


            if (y > getHeight() * 0.5) {//到底部边缘，pop要调整显示的位置
                pop.showAsDropDown(tagView, (tagView.getLeft() - x) + 50, (tagView.getTop() - y) - 100);
            } else {
                pop.showAsDropDown(tagView, (tagView.getLeft() - x) + 25, (tagView.getTop() - y) + 25);
            }
        });
    }


    /**
     * 清空点击的View
     *
     * @param view
     */
    private void removeItem(View view) {
        removeView(view);
    }

    /**
     * 移动标签
     *
     * @param x
     * @param y
     */
    private void moveView(int x, int y) {
        if (touchView == null) return;
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.leftMargin = x - startX + startTouchViewLeft;
        params.topMargin = y - startY + startTouchViewTop;
        //限制子控件移动必须在视图范围内
        if (params.leftMargin < 0 || (params.leftMargin + touchView.getWidth()) > getWidth())
            params.leftMargin = touchView.getLeft();
        if (params.topMargin < 0 || (params.topMargin + touchView.getHeight()) > getHeight())
            params.topMargin = touchView.getTop();
        touchView.setLayoutParams(params);
    }

    /**
     * 判断是否当前位置已经添加过通道配置
     *
     * @param x
     * @param y
     * @return 是否添加过tag
     */
    private boolean hasView(int x, int y) {
        //循环获取子view，判断xy是否在子view上，即判断是否按住了子view
        for (int index = 0; index < this.getChildCount(); index++) {
            View view = this.getChildAt(index);
            int left = (int) view.getX();
            int top = (int) view.getY();
            int right = view.getRight();
            int bottom = view.getBottom();
            Rect rect = new Rect(left, top, right, bottom);
            boolean contains = rect.contains(x, y);
            //如果是与子view重叠则返回真,表示已经有了view不需要添加新view了
            if (contains) {
                touchView = view;
                touchView.bringToFront();
                return true;
            }
        }
        touchView = null;
        return false;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(widthSpecSize, heightSpecSize);
        View child = getChildAt(0);
        if (child != null) {
            child.measure(widthMeasureSpec, heightMeasureSpec);
            setMeasuredDimension(widthSpecSize, heightSpecSize);
        }
    }
}
